<template>
  <div>
    <el-drawer
      title="选择提现订单"
      size="40%"
      :visible="isOpen"
      :direction="direction"
      @close="handleClose"
      :key="kay"
    >
      <div class="notInvoiced" ref="notInvoiced">
        <span>
          <li v-for="(inv, index) in WithdrawalList" :key="index">
            <div>
              <el-checkbox v-model="inv.isTrue"></el-checkbox>
            </div>

            <div class="invInfo">
              <h3>
                <b>{{ inv.name }} - {{ inv.title }}</b>
                <p>￥{{ (inv.updateTime ? inv.withdrawAmount : inv.amount) | sumFilters }}</p>
              </h3>
              <p>{{ inv.id }} · {{ inv.updateTime ? inv.updateTime : inv.createdTime }}</p>
              <!-- 查看明细的box -->
              <div class="detail-box">
                <h3 @click="clickUnfold(inv)">
                  <span v-if="unfoldOrder.id==inv.id">收起明细 <i class="el-icon-caret-top"></i></span>
                  <span v-else>展开明细 <i class="el-icon-caret-bottom"></i></span>
                </h3>
                <div v-if="unfoldOrder.id==inv.id">
                  <ul v-if="unfoldInfo.id">
                    <!-- 商务专员 -->
                    <li v-if="userRole.cmId && (userRole.cmId == unfoldInfo.cmId)">商务专员：¥{{unfoldInfo.cmCommission | sumFilters}}</li>
                    <!-- 商务经理 -->
                    <li v-if="userRole.cmId && (userRole.cmId == unfoldInfo.cmDirectorId)">商务经理：¥{{unfoldInfo.cmDirector | sumFilters}}</li>
                    <!-- 商务总监 -->
                    <li v-if="userRole.cmId && (userRole.cmId == unfoldInfo.cmSupervisorId)">商务总监：¥{{unfoldInfo.cmSupervisor | sumFilters}}</li>
                    <!-- 渠道专员 -->
                    <li v-if="userRole.placeId && (userRole.placeId == unfoldInfo.placeId)">渠道专员：¥{{unfoldInfo.placeCommission | sumFilters}}</li>
                    <!-- 渠道经理 -->
                    <li v-if="userRole.placeId && (userRole.placeId == unfoldInfo.placeDirectorId)">渠道经理：¥{{unfoldInfo.placeDirector | sumFilters}}</li>
                    <!-- 渠道总监 -->
                    <li v-if="userRole.placeId && (userRole.placeId === unfoldInfo.placeSupervisorId)">渠道总监：¥{{unfoldInfo.placeSupervisor | sumFilters}}</li>
                    
                    <!-- 专家分成 -->
                    <!-- 专家分成如果有更新时间updateTime就显示withdrawAmount字段，没有就显示unfoldInfo.expertCommission -->
                    <li v-if="userRole.expertId && (userRole.expertId == unfoldInfo.expertId)">专家分成：¥{{ getExpertAmount(inv) | sumFilters }}</li>

                    <!-- 实体收款人拨比 -->
                    <li v-if="userRole.paymentId && (userRole.paymentId == unfoldInfo.paymentId)">实体收款人拨比：¥{{unfoldInfo.organizationCommission | sumFilters}}</li>

                    <!-- 管拨收款人拨比 -->
                    <li v-if="userRole.operationsId && (userRole.operationsId == unfoldInfo.operationsId)">管拨收款人拨比：¥{{unfoldInfo.operations | sumFilters}}</li>
                  </ul>
                  <i class="el-icon-loading" v-else></i>
                </div>
              </div>
            </div>
          </li>
          <p class="moreBtn" @click="clickMoreBtn" v-if="WithdrawalList.length != this.total">更多<i class="el-icon-caret-bottom"></i></p>
        </span>

        <SubBtn>
          <template slot="btn">
            <div class="allSelectBox">
              <div class="left">
                <div style="display: flex; align-items: center">
                  <el-checkbox v-model="invCheckAll">全选</el-checkbox>
                  <!-- sumFilters -->
                  <p>共{{ getLength }}个订单，{{ getSelectAllMoney() |sumFilters }}元</p>
                </div>
              </div>
              <div class="right cashAmount">
                <el-button round @click="handleClose">取消</el-button>
                <el-button round :class="'cashIsFocus'" @click="comfirmFn">确认</el-button>
              </div>
            </div>
          </template>
        </SubBtn>
      </div>
    </el-drawer>
  </div>
</template>


<script>
import SubBtn from "@/components/subBtn/subBtn.vue";
import { amend,toDecimal } from "@/wss/utils/wss.js";
import { getConsumptionapilist } from "../../../api/myOrder/myOrder";
import { getOrderCommissionListApi } from "@/BMViews/api/financial/orderCommission.js";

import debounce from "lodash/debounce";
export default {
  name: 'withdrawOrder',
  components: { SubBtn },
  props: {
    WithdrawalList: {
      type: Array,
      // validator: (list, test) => {
      //   return true;
      // },
      default: () => [],
    },
    userRole: {
      type: Object,
      default() {
        return {};
      },
    },
    isOpen: {
      type: Boolean,
      default() {
        return false;
      },
    },
    total:{
      type: Number
    }
  },
  watch: {
    WithdrawalList: {
      deep: true,
      handler(list) {
        list.forEach((item) => {
          // item.isTrue = false
          // this.$set(item, "isTrue", false);
        });
        // console.log(val);
      },
    },
    isOpen:{
      handler(){
        if(this.isOpen){
          this.$nextTick(()=>{
            // this.$refs.notInvoiced.addEventListener("scroll", this.lazyLoading); // 滚动到底部，再加载的处理事件
          }) 
        }
      },
    }
  },
  data() {
    return {
      kay: "",
      getAllMoney: 0,
      getLength: "",
      userId: this.$store.state.user.userId,

      // 抽屉出来的方向
      direction: "rtl",

      selectAllMoney: 0,//当前选中的订单总价
      unfoldOrder:{},//当前展开的订单
      unfoldInfo:{},//当前展开的详细信息
      unfoldOrderList:[],//选择的提现订单列表
    };
  },
  mounted(){
    
  },
  computed: {
    invCheckAll: {
      get() {
        // 没有直接退出，默认就是false
        if (this.WithdrawalList.length == 0) return false;

        const { placeId, expertId, cmId } = this.userRole;

        // 过滤已选订单数组
        let selectArr = this.WithdrawalList.filter((item) => item.isTrue);
        // 获取已选订单
        this.getLength = selectArr.length;
        // 获取总价格
        this.getAllMoney = selectArr.reduce((prev, next) => {
          let Money = 0;
          switch (Number(this.$store.state.user.userType)) {
            case 50:
              return (prev = amend(prev, next.amount));
            case 60:
              for (const key in next) {
                if (next[key] == cmId) {
                  // 因为cmCommission 商务专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                  if (key == "cmId") {
                    Money = amend(Money, next.amount);
                    // Money = next.cmCommission;
                    continue;
                  }

                  Money = amend(Money, next[key.slice(0, -2)]);
                  // Money += next[key.slice(0, -2)];
                  // 把id截取掉，就是拨比key
                }
              }
              console.log(amend(prev, Money));
              return amend(prev, Money);
            // 商务和渠道
            case 69:
              // console.log(next, placeId, cmId, "出来出来");
              for (const key in next) {
                if (next[key] == placeId || next[key] == cmId) {
                  // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                  // 因为有多个角色所以要相加起来

                  if (key == "placeId") {
                    Money = amend(Money, next.amount);

                    // Money += next.placeCommission;
                    continue;
                  }
                  if (key == "cmId") {
                    Money = amend(Money, next.amount);
                    // Money += next.cmCommission;
                    continue;
                  }
                  // console.log(next[key.slice(0, -2)]);
                  if (next[key] == placeId || next[key] == cmId) {
                    // 把id截取掉，就是拨比key
                    // Money += next[key.slice(0, -2)];
                    Money = amend(Money, next[key.slice(0, -2)]);
                  }
                }
              }
              return amend(prev, Money);
            case 65:
              for (const key in next) {
                if (next[key] == placeId) {
                  if (key == "placeId") {
                    Money = amend(Money, next.amount);
                    // Money += next.placeCommission;
                    continue;
                  } // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行

                  // 把id截取掉，就是拨比key
                  // Money = amend(prev,next[key.slice(0, -2)]);
                  return amend(prev, next[key.slice(0, -2)]);
                }
              }
          }
        }, 0);
        // 是否全选
        return this.WithdrawalList.every((item) => item.isTrue == true);
      },
      set(val) {
        this.WithdrawalList.forEach((item) => {
          this.$set(item, "isTrue", val);
        });
        return !val;
      },
    },
    getPrice() {
      const { placeId, expertId, cmId } = this.userRole;
      // 10自己注册 00系统注册 40跟单 50专家 60商务 65渠道 69商务和渠道 80实体 90专家助理
      return (item) => {
        switch (Number(this.$store.state.user.userType)) {
          case 50:
            return item.expertCommission;

          case 60:
            for (const key in item) {
              if (item[key] == cmId) {
                if (key == "cmId") return item.cmCommission; // 因为cmCommission 商务专员的拨比属性和 placeId 的不一样，所以截取掉id也不行

                if (key == cmId) {
                  // 把id截取掉，就是拨比key
                  Money += item[key.slice(0, -2)];
                }
              }
            }

          case 65:
            for (const key in item) {
              if (item[key] == placeId) {
                if (key == "placeId") return item.placeCommission; // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                if (key == placeId) {
                  // 把id截取掉，就是拨比key
                  Money += item[key.slice(0, -2)];
                }
              }
            }
          // 商务和渠道
          case 69:
            let Money = 0;

            for (const key in item) {
              if (item[key] == placeId || item[key] == cmId) {
                // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                // 因为有多个角色所以要相加起来

                if (key == "placeId") {
                  Money += item.placeCommission;
                  continue;
                }
                if (key == "cmId") {
                  Money += item.cmCommission;
                  continue;
                }
                if (item[key] == placeId || item[key] == cmId) {
                  // 把id截取掉，就是拨比key
                  Money += item[key.slice(0, -2)];
                }
              }
            }
            console.log(Money, "我改我改");
            return Money;
            break;
        }
      };
    },
  },
  methods: {

    // 滚动到底部加载更多数据
    lazyLoading(e) {
      console.log(e);
      const scrollTop = e.target.scrollTop + 1; // 滚动条滚动时，距离顶部的距离
      const windowHeight = e.target.clientHeight; // 可视区的高度
      const scrollHeight = e.target.scrollHeight; // 滚动条的总高度
      // 滚动条到底部
      if (scrollTop + windowHeight >= scrollHeight) {
        // if(this.massgetabel.length >= this.total) return //获取完了就不用再获取了
        this.$emit("EventScrollLoadMore");//获取更多
      }
    },

    // 点击更多按钮获取更多
    clickMoreBtn: debounce(function(){
      if(this.WithdrawalList.length >= this.total) return //获取完了就不用再获取了
      this.$emit("EventScrollLoadMore");//获取更多
    },300),

    cleargetAllMoneyFn() {
      this.getAllMoney = 0;
    },

    //   确认按钮
    comfirmFn() {
      let WithdrawalList = this.WithdrawalList.filter((item) => item.isTrue);
      if (WithdrawalList.length <= 0) {
        this.$message({
          message: "请选择订单",
          type: "warning",
        });
        return;
      }
      this.$emit("EventGetAllMoney", this.selectAllMoney, WithdrawalList);
    },

    // 专家分成如果有更新时间updateTime就显示withdrawAmount字段，没有就显示unfoldInfo.expertCommission
    getExpertAmount(inv){
      if(inv.updateTime && inv.updateTime.length){
        return inv.withdrawAmount
      }else{
        return this.unfoldInfo.expertCommission
      }
    },

    //    获取提现订单
    // async getorderFn() {
    //   let { code, rows } = await getConsumptionapilist({
    //     userId: this.userId,
    //     status: 0,
    //   });
    //   if (code != 200) return;
    //   this.WithdrawalList = JSON.parse(JSON.stringify(rows));
    // },
    selectstatus() {},
    handleClose() {
      const _this = this;
      this.kay = Math.random();
      // _this.WithdrawalList = [];
      // _this.WithdrawalList.forEach((item) => {
      //   this.$set(item, "isTrue", false);
      // });

      // console.log(_this.WithdrawalList, "定下来");
      _this.$emit("update:isOpen", false);
    },

    // ------------------新的--------------
    // 计算当前选的价格
    getSelectAllMoney(){
      let arr = this.WithdrawalList.filter(item=>{
        return item.isTrue == true
      })
      let allNum = 0
      arr.forEach(item=>{
        if(item.updateTime){
          // 有更新时间
          allNum = amend(item.withdrawAmount,allNum)
        }else{
          // 无更新时间
          allNum = amend(item.amount,allNum)
        }
      })
      this.selectAllMoney = allNum
      return this.selectAllMoney
    },

    // 点击展开详情和收起详情
    clickUnfold(inv){
      if(this.unfoldOrder.id == inv.id){
        this.unfoldOrder = {}
      }else{
        this.unfoldOrder = inv
        this.unfoldInfo = {}// 获取前先清除之前的
        this.getOrderCommissionList(inv.id) //获取展开详情的接口
      }
    },

    // 获取展开详情的接口
    async getOrderCommissionList(orderId){
      let result = await getOrderCommissionListApi({orderId})
      if(result.code==200){
        this.unfoldInfo = result.rows[0]
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 抽屉样式 */
::v-deep .el-drawer__header {
  border-bottom: 1px solid #efefef;
  padding-bottom: 15px;
  margin-bottom: 20px;
}
::v-deep .el-drawer__header > span {
  font-size: 18px;
  font-weight: bold;
  color: #2e3f5e;
  padding-left: 20px;
  background: url("~@/wss/assets/image/icon/cardLeft.png") left center no-repeat;
  background-size: 7px;
}

/* 未开票样式 */
.notInvoiced {
  padding: 0px 20px 0;
  padding-bottom: 60px;
}
.notInvoiced ul {
  margin-bottom: 40px;
}
.notInvoiced .el-checkbox {
  margin-right: 10px;
}
::v-deep .notInvoiced .el-checkbox__label {
  display: none;
}

::v-deep .notInvoiced .el-checkbox .el-checkbox__inner {
  width: 24px;
  height: 24px;
  border-color: #bbbbbb;
  background: #fff;
  border-radius: 50%;
}
::v-deep .notInvoiced .el-checkbox .is-disabled .el-checkbox__inner {
  background: #f2f2f2;
}
::v-deep .notInvoiced .el-checkbox .is-checked .el-checkbox__inner {
  border-color: #f87a23;
  background: #f87a23;
}
::v-deep .notInvoiced .el-checkbox__input .el-checkbox__inner::after {
  content: "";
  width: 9px;
  height: 5px;
  border: 3px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 6px;
  left: 5px;
  vertical-align: middle;
  transform: rotate(0deg) scaleY(0);
  border-radius: 0px;
  background: none;
}
::v-deep
  .notInvoiced
  .el-checkbox__input.is-checked
  .el-checkbox__inner::after {
  transform: rotate(-45deg) scaleY(1);
}
.notInvoiced .invInfo {
  // flex-grow: 1;
  width: 95%;
  border-bottom: 1px solid #efefef;
  margin-bottom: 20px;
  padding-bottom: 20px;
}

.notInvoiced li {
  display: flex;
  flex-wrap: wrap;
}
.notInvoiced li > div:first-child {
  width: 5%;
}
/* .notInvoiced ul > li:hover {
  background-color: #f4f5f8;
} */

.notInvoiced li h3 {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin: 0;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 6px;
  margin-top: 3px;
}
.notInvoiced li h3 > span {
  font-weight: 400;
  font-size: 12px;
  color: #999;
}
.notInvoiced li h3 b {
  width: 85%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
.notInvoiced li h3 p {
  flex: 1;
  text-align: right;
  font-size: 14px;
  color: #333;
}
.notInvoiced li p {
  margin: 0;
  font-size: 12px;
  font-weight: 400;
  color: #999;
  line-height: 20px;
}

// 查看详情
.notInvoiced .invInfo .detail-box{
  background-color: #F7F7F7;
  padding: 10px;
  margin-top: 5px;
}
.notInvoiced .invInfo .detail-box>h3{
  display: block;
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  margin: 0;
  cursor: pointer;
}
.notInvoiced .invInfo .detail-box>div>i{
  margin-top: 5px;
}
.notInvoiced .invInfo .detail-box ul{
  margin: 0;
  padding: 0;
  display: flex;
  flex-wrap: wrap;
  border-top: 1px solid #E6E6E6;
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  margin-top: 10px;
  padding-top: 6px;
}
.notInvoiced .invInfo .detail-box ul>li{
  width: 33%;
  line-height: 22px;
}
// 查看详情

.allSelectBox {
  width: 100%;
  align-items: center;
  justify-content: space-between;
  display: flex;
}
.cashAmount {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cashAmount p {
  color: #39486f;
  font-size: 30px;
  font-weight: bold;
}
.cashAmount .el-button {
  border-color: #f87a23;
  color: #f87a23;
  font-weight: bold;
  font-size: 14px;
}
.cashAmount .el-button.cashIsFocus,
.cashAmount .el-button:hover {
  background-color: #f87a23;
  color: #fff;
}

// 更多按钮
.moreBtn{
  margin: 0;
  margin-bottom: 20px;
  text-align: center;
  font-size: 12px;
  color: #999;
  cursor: pointer;
}

/* 底部按钮 */
::v-deep .notInvoiced .subBtn {
  padding: 10px 20px!important;
  justify-content: space-between;
  align-items: center;
}
</style>